﻿using FrameworkCore.Migrations.Data;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

#nullable disable

namespace Domain.Entities.HealthManages;

/// <summary>
/// 健康档案表
/// </summary>
[Table("HealthRecords")]
public class HealthRecord : BaseAuditableEntity, ISoftDeletedEntity
{
    /// <summary>
    /// 关联用户ID（必须与用户表主键对应）
    /// </summary>
    public long? CustomerId { get; set; }

    public Customer? Customer { get; set; }

    /// <summary>
    /// 性别（存储格式示例：男/女/未知）
    /// </summary>
    [StringLength(4)]
    public string? Gender { get; set; }

    /// <summary>
    /// 出生日期（格式：yyyy-MM-dd）
    /// </summary>
    public DateTime? Birthday { get; set; }

    /// <summary>
    /// 身高（单位：厘米，可选）
    /// </summary>
    public decimal? Height { get; set; }

    /// <summary>
    /// 体重（单位：千克，可选）
    /// </summary>
    public decimal? Weight { get; set; }

    /// <summary>
    /// 血型（示例：A型/B型/AB型/O型）
    /// </summary>
    [StringLength(10)]
    public string? BloodType { get; set; }

    /// <summary>
    /// 血压（存储格式示例：120/80）
    /// </summary>
    [StringLength(20)]
    public string? BloodPressure { get; set; }

    /// <summary>
    /// 心率（单位：次/分钟，可选）
    /// </summary>
    public int? HeartRate { get; set; }

    /// <summary>
    /// 空腹血糖（单位：mmol/L，空腹8小时以上）
    /// </summary>
    public decimal? FastingBloodGlucose { get; set; }

    /// <summary>
    /// 餐后血糖（单位：mmol/L，餐后2小时测量）
    /// </summary>
    public decimal? PostprandialBloodGlucose { get; set; }

    /// <summary>
    /// 随机血糖（单位：mmol/L，任意时间测量）
    /// </summary>
    public decimal? RandomBloodGlucose { get; set; }

    /// <summary>
    /// 糖化血红蛋白（HbA1c，单位：%，反映近3个月血糖平均水平）
    /// </summary>
    public decimal? GlycatedHemoglobin { get; set; }

    /// <summary>
    /// 血糖测量时间（记录最后一次测量的时间）
    /// </summary>
    public DateTime? GlucoseMeasureTime { get; set; }

    /// <summary>
    /// 血糖趋势标识（0: 平稳，1: 上升，2: 下降）
    /// </summary>
    public int? GlucoseTrend { get; set; }

    /// <summary>
    /// 检查结果（可存储JSON或文本描述）
    /// </summary>
    public string? Result { get; set; }

    /// <summary>
    /// 软删除标志
    /// </summary>
    public bool? IsDeleted { get ; set; }

    /// <summary>
    /// 生成格式化的健康记录描述
    /// </summary>
    public string ToHealthSummaryString()
    {
        return
            $"性别: {Gender ?? "未提供"}\n" +
            $"出生日期: {Birthday?.ToString("yyyy-MM-dd") ?? "未提供"}\n" +
            $"身高: {Height?.ToString("0.0")} 厘米\n" +
            $"体重: {Weight?.ToString("0.0")} 千克\n" +
            $"血型: {BloodType ?? "未提供"}\n" +
            $"血压: {BloodPressure ?? "未提供"}\n" +
            $"心率: {HeartRate?.ToString() ?? "未提供"} 次/分钟\n" +
            $"空腹血糖: {FastingBloodGlucose?.ToString("0.0")} mmol/L\n" +
            $"餐后血糖: {PostprandialBloodGlucose?.ToString("0.0")} mmol/L\n" +
            $"随机血糖: {RandomBloodGlucose?.ToString("0.0")} mmol/L\n" +
            $"糖化血红蛋白: {GlycatedHemoglobin?.ToString("0.0")}%\n" +
            $"血糖测量时间: {GlucoseMeasureTime?.ToString("yyyy-MM-ddTHH:mm:ssZ") ?? "未记录"}";
    }

    /// <summary>
    /// 生成AI分析使用的结构化JSON数据
    /// </summary>
    public string ToAIHealthDataJson()
    {
        int? age = null;
        if (Birthday.HasValue)
        {
            age = DateTime.Today.Year - Birthday.Value.Year;
            if (Birthday.Value.Date > DateTime.Today.AddYears(-age.Value)) age--;
        }

        decimal? bmi = null;
        if (Height.HasValue && Height > 0 && Weight.HasValue)
        {
            bmi = Weight.Value / ((Height.Value / 100) * (Height.Value / 100));
        }

        int? systolic = null;
        int? diastolic = null;
        if (!string.IsNullOrEmpty(BloodPressure) && BloodPressure.Contains('/'))
        {
            var parts = BloodPressure.Split('/');
            if (parts.Length >= 2 && int.TryParse(parts[0], out var sys) && int.TryParse(parts[1], out var dia))
            {
                systolic = sys;
                diastolic = dia;
            }
        }

        return $$"""
        {
          "health_record": {
            "basic_info": {
              "gender": "{{Gender ?? "N/A"}}",
              "birthday": "{{Birthday?.ToString("yyyy-MM-dd") ?? "N/A"}}",
              "age": {{(age?.ToString() ?? "null")}}
            },
            "vital_signs": {
              "height": {{(Height?.ToString("0.0") ?? "null")}},
              "weight": {{(Weight?.ToString("0.0") ?? "null")}},
              "bmi": {{(bmi?.ToString("0.0") ?? "null")}}
            },
            "cardiovascular": {
              "blood_pressure": "{{BloodPressure ?? "N/A"}}",
              "systolic": {{(systolic?.ToString() ?? "null")}},
              "diastolic": {{(diastolic?.ToString() ?? "null")}},
              "heart_rate": {{(HeartRate?.ToString() ?? "null")}}
            },
            "metabolic": {
              "fasting_glucose": {{(FastingBloodGlucose?.ToString("0.0") ?? "null")}},
              "postprandial_glucose": {{(PostprandialBloodGlucose?.ToString("0.0") ?? "null")}},
              "random_glucose": {{(RandomBloodGlucose?.ToString("0.0") ?? "null")}},
              "hba1c": {{(GlycatedHemoglobin?.ToString("0.0") ?? "null")}},
              "measurement_time": "{{GlucoseMeasureTime?.ToString("yyyy-MM-ddTHH:mm:ssZ") ?? "N/A"}}"
            },
            "blood_type": "{{BloodType ?? "N/A"}}"
          },
          "requested_analysis": [
            "assess_diabetes_risk",
            "generate_lifestyle_recommendations",
            "identify_health_anomalies"
          ],
          "clinical_context": {
            "reference_ranges": {
              "hba1c": [4.0, 5.6],
              "fasting_glucose": [3.9, 6.1],
              "postprandial_glucose": [0, 7.8],
              "blood_pressure": [90, 120, 60, 80]
            }
          }
        }
        """;
    }
}

public enum GlucoseType
{
    Fasting = 1,        // 空腹
    Postprandial = 2,    // 餐后
    BeforeBed = 3,       // 睡前
    Random = 4           // 随机
}